<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="doLogin">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          :loading="isLoading"
          loading-text="登录中..."
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from "@/api";
// import { setToken } from "@/utils/auth";
export default {
  data() {
    return {
      mobile: "",
      code: "",
      isLoading: false,
      rules: {
        mobile: [
          { required: true, message: "请填写手机号" },
          {
            pattern: /^1[2-9]\d{9}$/,
            message: "请填写正确的手机号",
            trigger: "onChange",
          },
        ],
        code: [
          { required: true, message: "请填写验证码" },
          {
            pattern: /^\d{6}$/,
            message: "请填写6位数字验证码",
            trigger: "onChange",
          },
        ],
      },
    };
  },
  methods: {
    async doLogin(data) {
      this.isLoading = true;
      try {
        let res = await loginAPI(data);
        this.$toast.success("登陆成功");

        // console.log(res.data.data.token);
        this.$store.commit("saveToken", res.data.data);

        // 调用获取用户信息的方法
        this.$store.dispatch('reqUserInfo')
        if (this.$route.query.back) {
          this.$router.push(this.$route.query.back);
        } else {
          this.$router.push({
            name: "home",
          });
        }

        // setToken(res.data.data);
      } catch {
        this.$toast.fail("登陆失败");
      }
      this.isLoading = false;
      // loginAPI(data)
      // .then((res) => {
      // console.log(res);
      //   this.$toast("登陆成功");
      // this.$toast.success("登陆成功");
      // })
      // .catch((res) => {
      //   this.$toast("登陆失败");
      //   Toast.fail("失败文案");报错
      // this.$toast.fail("登陆失败");
      // })
      // .finally(() => {
      // this.isLoading = false;
      // });
    },
  },
};
</script>

<style>
</style>